package com.wswy.wzcx.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.NetworkUtils.NetworkType;
import com.blankj.utilcode.util.SPUtils;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.module.ScTimes;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import timber.log.Timber;


public class SecurityCheckerUtils {
    private static final String[] KNOWN_DANGEROUS_APPS_PACKAGES;
    private static final String[] KNOWN_ROOT_APPS_PACKAGES;
    private static final String[] KNOWN_ROOT_CLOAKING_PACKAGES;
    private static final String[] PATHS_THAT_SHOULD_NOT_BE_WRTIABLE;
    private static final String[] SU_PATHS = {"/data/local/", "/data/local/bin/", "/data/local/xbin/", "/sbin/", "/system/bin/", "/system/bin/.ext/", "/system/bin/failsafe/", "/system/sd/xbin/", "/system/usr/we-need-root/", "/system/xbin/"};

    static {
        PATHS_THAT_SHOULD_NOT_BE_WRTIABLE = new String[]{"/system", "/system/bin", "/system/sbin", "/system/xbin", "/vendor/bin", "/sbin", "/etc"};
        KNOWN_DANGEROUS_APPS_PACKAGES = new String[]{"com.koushikdutta.rommanager", "com.dimonvideo.luckypatcher", "com.chelpus.lackypatch", "com.ramdroid.appquarantine"};
        KNOWN_ROOT_CLOAKING_PACKAGES = new String[]{"com.devadvance.rootcloak", "de.robv.android.xposed.installer", "com.saurik.substrate", "com.devadvance.rootcloakplus", "com.zachspong.temprootremovejb", "com.amphoras.hidemyroot", "com.formyhm.hideroot"};
        KNOWN_ROOT_APPS_PACKAGES = new String[]{"com.noshufou.android.su", "com.noshufou.android.su.elite", "eu.chainfire.supersu", "com.koushikdutta.superuser", "com.thirdparty.superuser", "com.yellowes.su","com.topjohnwu.magisk"};
    }

    private static boolean checkForBinary(String paramString) {
        int l = 0;
        String[] arrayOfString = SU_PATHS;
        int j = arrayOfString.length;
        int i = 0;
        while (i < j) {
            String str = arrayOfString[i];
            str = str + paramString;
            int k = l;
            if (new File(str).exists()) {
                k = 1;
            }
            ++i;
            l = k;
        }
        return l != 0;
    }


    private static boolean isAnyPackageFromListInstalled(Context paramContext, String[] paramList) {
        PackageManager pm = paramContext.getPackageManager();
        for (String str2 : paramList) {
            try {
                pm.getPackageInfo(str2, 0);
                return true;
            } catch (Throwable localNameNotFoundException) {
                localNameNotFoundException.printStackTrace();
            }
        }
        return false;
    }

    private static boolean hasProxy(){
        String proxyAddress = System.getProperty("http.proxyHost");
        String proxyPort = System.getProperty("http.proxyPort");

        return !TextUtils.isEmpty(proxyAddress) && !TextUtils.isEmpty(proxyPort);
    }


    private static String getProxy(){
        return System.getProperty("http.proxyHost")+":"+System.getProperty("http.proxyPort");
    }

    public static boolean hasRoot(Context context) {
        return checkForBinary("su")
                || isAnyPackageFromListInstalled(context, KNOWN_ROOT_APPS_PACKAGES)
                || isAnyPackageFromListInstalled(context, KNOWN_DANGEROUS_APPS_PACKAGES)
                || isAnyPackageFromListInstalled(context, KNOWN_ROOT_CLOAKING_PACKAGES);
    }



    private static Boolean notHasLightSensorManager(Context context) {
        try {
            SensorManager sensorManager = (SensorManager) context
                .getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor8 = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); //光
            if (null == sensor8) {
                return true;
            } else {
                return false;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    private static boolean isEmulator() {
        return Build.FINGERPRINT.startsWith("generic")
            || Build.FINGERPRINT.toLowerCase().contains("vbox")
            || Build.FINGERPRINT.toLowerCase().contains("test-keys")
            || Build.MODEL.contains("google_sdk")
            || Build.MODEL.contains("Emulator")
            || Build.MODEL.contains("Android SDK built for x86")
            || Build.MANUFACTURER.contains("Genymotion")
            || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
            || "google_sdk".equals(Build.PRODUCT);
    }

    private static boolean checkDebuggable(Context context){
        return (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    }


    public static boolean checkAvailable(Context context){
        Timber.e("hasProxy:"+hasProxy());
        Timber.e("isEmulator:"+isEmulator());
        Timber.e("hasRoot:"+hasRoot(context));
        Timber.e("notHasLightSensorManager:"+notHasLightSensorManager(context));
        Timber.e("checkDebuggable:"+checkDebuggable(context));
        boolean s =  hasProxy() ||  isEmulator() || hasRoot(context) || notHasLightSensorManager(context) || checkDebuggable(context);

        return !s;
    }


    public static void aaa(Context context){
        Map<String,Object> map = new HashMap<>();
        map.put("has_proxy",getProxy()); //代理地址
        map.put("has_root",hasRoot(context)); //root
        map.put("is_emulator",isEmulator());  //是否模拟器
        map.put("light_sensor",String.valueOf(notHasLightSensorManager(context))); //光线传感器
        //map.put("start_time", AppContext.START_TIME);  //启动时间
        map.put("ad_time","");    //广告时间

        map.put("app_install_time",""); //安装时间
        map.put("app_upgrade_time","");  //更新时间

        map.put("device_model",Build.MODEL);  //设备信息
        map.put("device_manufacture",Build.MANUFACTURER);
        map.put("device_brand",Build.BRAND);
        map.put("device_product",Build.PRODUCT);
        map.put("device",Build.DEVICE);
        map.put("device_fingerprint",Build.FINGERPRINT);

        //mac地址
        //设备id
        //android_id
        //

        Timber.e("map: "+map);
    }

    public static String getNetWorkType() {
        NetworkType networkType = NetworkUtils.getNetworkType();
        switch (networkType) {
            case NETWORK_2G:
                return "2G";
            case NETWORK_3G:
                return "3G";
            case NETWORK_4G:
                return "4G";
            case NETWORK_WIFI:
                return "WIFI";
            case NETWORK_ETHERNET:
                return "ethernet";
            default:
                return "unknown";
        }
    }

    public static String getWIFISSID(Context  context) {
        String ssid="unknown";

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O || Build.VERSION.SDK_INT==Build.VERSION_CODES.P) {

            WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            assert mWifiManager != null;
            WifiInfo info = mWifiManager.getConnectionInfo();

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                return info.getSSID();
            } else {
                return info.getSSID().replace("\"", "");
            }
        } else if (Build.VERSION.SDK_INT==Build.VERSION_CODES.O_MR1){
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            assert connManager != null;
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected()) {
                if (networkInfo.getExtraInfo()!=null){
                    return networkInfo.getExtraInfo().replace("\"","");
                }
            }
        }
        return ssid;
    }



    public static boolean canRequestCode(){
        long lastBanTime = SPUtils.getInstance().getLong("smlbt");
        //记录多次发送时间，
        if (lastBanTime > 0 && System.currentTimeMillis() - lastBanTime < 60*1000){
            return false;
        }

        boolean canSend = false;

        long count = ScTimes.getSendSMSCount();

        //如果
        if (count > 3 && !checkAvailable(AppContext.getContext())){
            canSend =  false;
        }else {
            canSend = ScTimes.getSendSMSCount() < 5 ;
        }
        
        if (!canSend){
            SPUtils.getInstance().put("smlbt",System.currentTimeMillis());
        }

        return canSend;
    }

}